package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.cache.FileManager;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.component.CityAndMarketDialog;
import com.aoxon.cargo.component.MyCallBack;
import com.aoxon.cargo.component.MyListDialog;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.component.MySquarePicture;
import com.aoxon.cargo.component.MyTextWatcher;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.FileUpLoadService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RevampStoreService;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyReturnState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ImageUtil;
import com.aoxon.cargo.util.ToastUtil;

/**
 * 店铺信息填写界面
 * 
 * @author ZZJ
 * 
 */
public class SupStoreInformationActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private EditText etCompanyName;
	private EditText etStoreName;
	private EditText etStallNumber;
	private EditText etPhoneNumber;

	private ImageView ivStoreLogo;
	private ImageView ivReturnButton;
	private ImageView ivCommitButton;
	private ImageView ivStoreLogoAddButton;
	private ImageView ivStoreFecadeAddButton;

	private TextView tvTitle;
	private TextView tvCity;
	private TextView tvMarket;

	private ProgressBar pbLogoLoading;

	private LinearLayout llHolder;
	private LinearLayout llStoreFecade;
	private RelativeLayout rlStoreLogo;

	private MyListDialog myListDialog;
	private MyTextWatcher myTextWatcher;
	private MyProgressDialog myProgressDialog;
	private MySquarePicture mySquarePicture;
	private CityAndMarketDialog showCityAndMarketDialog;

	private GsonBean supGsonBean;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private FileManager imageManager = new FileManager();
	private FileLoader imageLoader = new FileLoader(200, 200, false);
	private List<Picture> logoPictureList = new ArrayList<Picture>();
	private List<Picture> fecadePictureList = new ArrayList<Picture>();

	private FileUpLoadService fileUpLoadService = new FileUpLoadService();

	private RevampStoreService revampStoreService = (RevampStoreService) MyServiceFactory
			.getInstance(MyServiceFactory.REVAMP_STORE);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();
		beginShow();

	}


	/**
	 * 自定义方法
	 * ******************************************************************************************************************************************/

	private void setup() {
		setContentView(R.layout.sup_input_store_information);

		etCompanyName = (EditText) findViewById(R.id.etInformationCompanyName);
		etStoreName = (EditText) findViewById(R.id.etInformationStoreName);
		etStallNumber = (EditText) findViewById(R.id.etInformationStallNumber);
		etPhoneNumber = (EditText) findViewById(R.id.etInformationPhoneNumber);

		ivStoreLogo = (ImageView) findViewById(R.id.ivInformationStoreLogo);
		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivCommitButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		ivStoreLogoAddButton = (ImageView) findViewById(R.id.ivInformationStoreLogoAddButton);
		ivStoreFecadeAddButton = (ImageView) findViewById(R.id.ivInformationStoreFecadeAddButton);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		tvCity = (TextView) findViewById(R.id.tvInformationCity);
		tvMarket = (TextView) findViewById(R.id.tvInformationMarket);

		pbLogoLoading = (ProgressBar) findViewById(R.id.pbInformationStoreLogo);

		llHolder = (LinearLayout) etCompanyName.getParent().getParent();
		llStoreFecade = (LinearLayout) findViewById(R.id.llInformationStoreFecade);
		rlStoreLogo = (RelativeLayout) findViewById(R.id.rlInformationStoreLogo);

		myListDialog = new MyListDialog(this);
		myProgressDialog = new MyProgressDialog(this);
		myTextWatcher = new MyTextWatcher(new textWhatcherBack());
		mySquarePicture = new MySquarePicture(this, llStoreFecade, true);
		showCityAndMarketDialog = new CityAndMarketDialog(this,
				normalDataLoader.getHandler(), tvCity, tvMarket);

		normalDataLoader.setOnloadDataListener(this);

		tvTitle.setText("店铺信息");
		ivCommitButton.setImageResource(R.drawable.button_public_commit);
		ivCommitButton.setEnabled(false);

		etCompanyName.addTextChangedListener(myTextWatcher);
		etStoreName.addTextChangedListener(myTextWatcher);
		etStallNumber.addTextChangedListener(myTextWatcher);
		etPhoneNumber.addTextChangedListener(myTextWatcher);
		tvCity.addTextChangedListener(myTextWatcher);
		tvMarket.addTextChangedListener(myTextWatcher);

		tvCity.setOnClickListener(myClickListener);
		tvMarket.setOnClickListener(myClickListener);
		ivStoreLogo.setOnClickListener(myClickListener);
		ivReturnButton.setOnClickListener(myClickListener);
		ivCommitButton.setOnClickListener(myClickListener);
		ivStoreFecadeAddButton.setOnClickListener(myClickListener);
		ivStoreLogoAddButton.setOnClickListener(myClickListener);
		llHolder.setOnClickListener(myClickListener);
	}

	/**
	 * 初始化显示
	 */
	private void beginShow() {
		try {

			Supplier supplier = SupIndexShared.getSupplier();
			if (!supplier.getSupCount().equals("")
					|| !supplier.getSupPassword().equals("")) {

				etCompanyName.setText(supplier.getSupCompanyFullName());
				etStoreName.setText(supplier.getStoreName().toString());
				tvCity.setText(supplier.getSupCity());
				tvMarket.setText(supplier.getsupMarket());
				etStallNumber.setText(supplier.getsupStall());
				etPhoneNumber.setText(supplier.getSupPhone());

				try {
					Picture picture = supplier.getSupLogo().get(0);
					if (picture != null) {
						rlStoreLogo.setVisibility(View.VISIBLE);
						String path = picture.getPictureUrl() + "s.png";
						imageLoader.displayImage(path, ivStoreLogo,
								pbLogoLoading, false);
						ivStoreLogoAddButton.setVisibility(View.GONE);
						logoPictureList.add(supplier.getSupLogo().get(0));
					}
				} catch (Exception e) {
					e.printStackTrace();
					pbLogoLoading.setVisibility(View.GONE);
				}

				for (int i = 0; i < supplier.getSupCompanyPicture().size(); i++) {
					Picture picture = supplier.getSupCompanyPicture().get(i);
					mySquarePicture.show(picture);
					fecadePictureList.add(picture);
				}
				SupCache.pictureList = fecadePictureList;

			} else {
				EnvironmentUtil.errorLogin(SupStoreInformationActivity.this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据路径获取显示图片
	 * 
	 * @param path
	 */
	private void getImageViewToStoreLogo(String path) {
		try {
			ivStoreLogo.setTag(path);
			Bitmap bitmap = ImageUtil.getImageBitmap(path, 200, 200);
			ivStoreLogo.setImageBitmap(ImageUtil.imageCropToSquare(bitmap));
			rlStoreLogo.setVisibility(View.VISIBLE);
			ivStoreLogoAddButton.setVisibility(View.GONE);
			int n = 0;
			for (; n < logoPictureList.size(); n++) {
			}
			n--;
			switch (logoPictureList.get(n).getPictureState()) {
			case DataState.INITIAL:
				logoPictureList.remove(n);
				break;
			case DataState.ADD:
				logoPictureList.get(n).setPictureState(
						DataState.HAVE_BUT_DELETE);
				break;
			case DataState.SUCCESS:
				logoPictureList.get(n).setPictureState(DataState.DELETE);
				break;
			default:
				break;
			}
			ivCommitButton.setEnabled(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断要提交填写的资料格式是否正确
	 * 
	 * @return
	 */
	private boolean checkApplyData() {
		List<String> strList = getInputList();

		if (strList.get(0).length() >= 24) {
			etCompanyName.requestFocus();
			ToastUtil.show(this, "公司名称不能超过24个字符");
			return false;
		}
		if (strList.get(1).length() >= 24) {
			etStoreName.requestFocus();
			ToastUtil.show(this, "店铺名称不能超过24个字符");
			return false;
		}
		if (strList.get(2).equals("") || strList.get(2) == null) {
			tvCity.requestFocus();
			ToastUtil.show(this, "请选择所在城市");
			return false;
		}
		if (strList.get(3).equals("") || strList.get(3) == null) {
			tvMarket.requestFocus();
			ToastUtil.show(this, "请选择批发市场");
			return false;
		}
		if (strList.get(4).equals("") || strList.get(4) == null) {
			etStallNumber.requestFocus();
			ToastUtil.show(this, "档口号码不能为空");
			return false;
		}
		if (!strList.get(5).matches(
				"^([0-9]{3}-?[0-9]{8})|([0-9]{4}-?[0-9]{7})$")) {
			etPhoneNumber.requestFocus();
			ToastUtil.show(this, "请填写正确的电话号码");
			return false;
		}

		return true;
	}

	/**
	 * 获取所有输入框的文本列表
	 * 
	 * @return
	 */
	private List<String> getInputList() {
		List<String> strList = new ArrayList<String>();

		strList.add(etCompanyName.getText().toString());
		strList.add(etStoreName.getText().toString());
		strList.add(tvCity.getText().toString());
		strList.add(tvMarket.getText().toString());
		strList.add(etStallNumber.getText().toString());
		strList.add(etPhoneNumber.getText().toString());

		return strList;
	}

	/**
	 * 判断是否有图片输入 状态3是已经上传但中断又被删时给的状态
	 * 
	 * @param pictures
	 * @return
	 */
	private boolean checkInputPicture(List<Picture> pictures) {
		for (int i = 0; i < pictures.size(); i++) {
			if (DataState.HAVE_BUT_DELETE != pictures.get(i).getPictureState()) {
				return true;
			}
		}
		return false;

	}

	/**
	 * 判断所有输入框是否都有输入
	 * 
	 * @return
	 */
	private void checkAllInput() {
		List<String> strList = getInputList();

		for (int i = 0; i < strList.size(); i++) {
			if (strList.get(i).equals("") || strList.get(i) == null) {
				ivCommitButton.setEnabled(false);
				return;
			}
		}

		if (!checkInputPicture(fecadePictureList)
				|| !checkInputPicture(logoPictureList)) {
			ivCommitButton.setEnabled(false);
			return;
		}
		ivCommitButton.setEnabled(true);
	}

	private void commitResult() {

		try {
			if (CheckStateUtil.check(getBaseContext(), supGsonBean, "信息修改")) {
				ToastUtil.show(getBaseContext(), "店铺信息修改成功！");
				String strSupplier = supGsonBean.getStrJson();
				SupIndexShared.saveSupplierAndKey(strSupplier);
				Intent intent = new Intent(getBaseContext(),
						SupSettingActivity.class);
				startActivity(intent);
				this.finish();
			} else {
				ToastUtil.show(getBaseContext(), "帐号密码出错，请重新登录！");
			}

		} catch (Exception e) {
			ToastUtil.show(getBaseContext(), "用户资料提交失败，请重新提交！");
		}

	}

	/**
	 * 
	 * 
	 */
	class TakePhotoForStoreLogo implements MyCallBack {
		@Override
		public void callback(String choose) {
			if (choose.equals("拍照")) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, MyStateUtil.CAMERA_for_LOGO);
			} else {
				try {
					Intent intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent, MyStateUtil.FOLDER_for_LOGO);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	class TakePhotoForStoreFecade implements MyCallBack {
		@Override
		public void callback(String choose) {
			if (choose.equals("拍照")) {
				if (!SupCache.initialCamera) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							MyStateUtil.CAMERA_for_FECADE);
				} else {
					Intent intent = new Intent(getBaseContext(),
							SupCameraActivity.class);
					SupCache.pictureList = fecadePictureList;
					startActivityForResult(intent, MyStateUtil.CAMERA_TO_ADD);
				}
			} else {
				try {
					Intent intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent,
							MyStateUtil.FOLDER_for_FECADE);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}

	/**
	 * 文本监听的回调
	 */
	class textWhatcherBack implements MyCallBack {

		@Override
		public void callback(String choose) {
			checkAllInput();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Bitmap bitmap = null;
		String path = null;
		if (resultCode == RESULT_OK) {

			Picture picture = new Picture();
			picture.setPictureState(DataState.INITIAL);

			switch (requestCode) {
			case MyStateUtil.CAMERA_for_LOGO:
				bitmap = data.getParcelableExtra("data");
				path = imageManager.saveBitmap(bitmap);
				getImageViewToStoreLogo(path);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.LOGO_TYPE);
				logoPictureList.add(picture);
				break;

			case MyStateUtil.CAMERA_for_FECADE:
				bitmap = data.getParcelableExtra("data");
				path = imageManager.saveBitmap(bitmap);
				mySquarePicture.getImageView(path, false);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.STALL_TYPE);
				fecadePictureList.add(picture);
				break;

			case MyStateUtil.FOLDER_for_LOGO:
				path = ImageUtil.getAbsoluteImagePath(data.getData(), this);
				getImageViewToStoreLogo(path);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.LOGO_TYPE);
				logoPictureList.add(picture);
				break;

			case MyStateUtil.FOLDER_for_FECADE:
				path = ImageUtil.getAbsoluteImagePath(data.getData(), this);
				mySquarePicture.getImageView(path, false);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.STALL_TYPE);
				fecadePictureList.add(picture);
				break;

			case MyStateUtil.CAMERA_TO_ADD:
			case MyStateUtil.GALLERY_RETURN:
				llStoreFecade.removeAllViews();
				for (int i = 0; i < SupCache.pictureList.size(); i++) {
					picture = SupCache.pictureList.get(i);
					mySquarePicture.show(picture);
				}
				fecadePictureList = SupCache.pictureList;
				break;
			default:
				break;
			}
			checkAllInput();
		}

	}

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(getBaseContext(),
					SupSettingActivity.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	/**
	 * 设置各控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			EnvironmentUtil.closeInputMethod(SupStoreInformationActivity.this);

			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				Intent intent = new Intent(getBaseContext(),
						SupSettingActivity.class);
				startActivity(intent);
				SupStoreInformationActivity.this.finish();
				break;

			case R.id.ivPublicTitleOther:
				if (checkApplyData()) {
					normalDataLoader.load();
				}
				break;

			case R.id.ivInformationStoreLogo:
			case R.id.ivInformationStoreLogoAddButton:
				myListDialog.show("请选择", new String[] { "拍照", "本地文件" },
						new TakePhotoForStoreLogo());
				break;

			case R.id.ivInformationStoreFecadeAddButton:
				myListDialog.show("请选择", new String[] { "拍照", "本地文件" },
						new TakePhotoForStoreFecade());
				break;

			case R.id.tvInformationCity:
				showCityAndMarketDialog.showCity();
				break;

			case R.id.tvInformationMarket:
				showCityAndMarketDialog.showMarket();
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myProgressDialog.show("提示", "提交中，请稍候...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		try {
			for (int i = 0; i < fecadePictureList.size(); i++) {
				Picture picture = fecadePictureList.get(i);
				if (picture.getPictureState() == DataState.INITIAL) {
					GsonBean gsonBean = fileUpLoadService.upLoadPicture(picture
							.getPictureUrl());
					if (CheckStateUtil.check(gsonBean)) {
						Picture pictureReturn = DataUtil.gson.fromJson(
								gsonBean.getStrJson(), Picture.class);
						fecadePictureList.set(i, pictureReturn);
					}
				}
			}

			if (EnvironmentUtil.checkNetState(getBaseContext())) {
				for (int i = 0; i < logoPictureList.size(); i++) {
					Picture picture = logoPictureList.get(i);
					if (picture.getPictureState() == DataState.INITIAL) {
						GsonBean gsonBean = fileUpLoadService
								.upLoadPicture(picture.getPictureUrl());
						if (CheckStateUtil.check(gsonBean)) {
							Picture pictureReturn = DataUtil.gson.fromJson(
									gsonBean.getStrJson(), Picture.class);
							logoPictureList.set(i, pictureReturn);
						}
					}
				}
			} else {
				msg.what = MyStateUtil.NOT_NET_CONNECTION;
			}

			List<String> strList = getInputList();
			Supplier supplier = SupIndexShared.getSupplier();
			supplier.setSupCompanyPicture(fecadePictureList);
			supplier.setSupLogo(logoPictureList);
			supplier.setSupCompanyFullName(strList.get(0));
			supplier.setStoreName(strList.get(1));
			supplier.setSupCity(strList.get(2));
			supplier.setsupMarket(strList.get(3));
			supplier.setsupStall(strList.get(4));
			supplier.setSupPhone(strList.get(5));

			if (EnvironmentUtil.checkNetState(getBaseContext())) {
				supGsonBean = revampStoreService.execute(supplier);
				msg.what = MyStateUtil.UPLOAD_RESULT;
			} else {
				msg.what = MyStateUtil.NOT_NET_CONNECTION;
			}
		} catch (Exception e) {
			msg.what = MyStateUtil.UPLOAD_ERROR;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myProgressDialog.cancle();
		switch (state) {
		case MyStateUtil.UPLOAD_RESULT:
			commitResult();
			break;
		case MyStateUtil.UPLOAD_ERROR:
			ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
			break;
		case MyStateUtil.GET_CITY_RESULT:
			showCityAndMarketDialog.showCity();
			break;
		case MyStateUtil.GET_MARKET_RESULT:
			showCityAndMarketDialog.showMarket();
			break;
		case MyStateUtil.RETURN_FAIL:
			ToastUtil.show(getBaseContext(), "无对应数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "无网络连接");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			break;
		}
	}

}
